package com.wuyan.wupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.wuyan.wupicturebackend.exception.BusinessException;
import com.wuyan.wupicturebackend.exception.ErrorCode;
import com.wuyan.wupicturebackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * Url图片上传
 */
@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        //校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"文件不能为空");
        //校验URL格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式地址不正确");
        }
        //发送HEAD请求校验文件是否存在
        HttpResponse httpResponse = null;
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR,"仅支持HTTP或HTTPS协议的文件地址");
        //文件存在，文件类型校验
        try {
            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            //文件存在，文件大小校验
            String contentType = httpResponse.header("Content-Type");
            //不为空，才校验是否合法
            if(StrUtil.isNotBlank(contentType)){
                //允许的图片类型
                List<String> ALLOW_CONTE_TYPES = Arrays.asList("image/jpg","image/jpeg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTE_TYPES.contains(contentType), ErrorCode.PARAMS_ERROR,"文件类型错误");
            }
            //文件存在，文件大小校验
            String contentLength = httpResponse.header("Content-Length");
            if(StrUtil.isNotBlank(contentLength)){
                try {
                    long contentLengthLong = Long.parseLong(contentLength);
                    final long ONE_M = 1024 * 1024;
                    ThrowUtils.throwIf(contentLengthLong > 2 * ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过2MB");
                }catch (NumberFormatException e){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }
            }
        }catch (Exception e){
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
        finally {
            //释放资源
            if(httpResponse != null){
                httpResponse.close();
            }
        }
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        //下载文件
        HttpUtil.downloadFile(fileUrl, file);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        String originalFileName = FileUtil.mainName(fileUrl);
        return originalFileName;
    }
}
